<template>
  <div class="knowledge-detail">
    <CommonNavigateBar title="知识详情" />
    <div class="knowledge-detail__wrapped">
      <div class="knowledge-detail__content">
        <CommonScroll
          :pulldown-enabled="false"
          :pullup-enabled="false"
          @scroll-to-lower="onScrollToLower"
        >
          <div class="knowledge-detail__header">
            <div class="knowledge-detail__header-title">
              {{ detail && detail.name }}
            </div>
            <div class="knowledge-detail__header-info">
              <span>作者：{{ detail && detail.author }}</span>
              <span>浏览量：{{ detail && detail.viewCount }}</span>
            </div>
          </div>

          <div class="knowledge-detail__article">
            <div
              v-if="detail && detail.videos"
              class="knowledge-detail__article-video"
            >
              <video
                v-for="(url, index) in detail.videos"
                :key="index"
                :src="url"
                :disable-progress="true"
                @timeupdate="onTimeUpdate"
                @ended="onEnded"
              />
            </div>
            <mp-html
              :content="html"
              :copy-link="false"
              class="knowledge-detail__article-label"
            ></mp-html>
          </div>
        </CommonScroll>
      </div>
      <div class="knowledge-detail__footer">
        <div class="knowledge-detail__footer-wrapped">
          <div class="operate-item" @tap="onLike">
            <image
              v-show="detail && detail.hasLiked"
              src="@/assets/icon/big-like-selected.png"
              class="like-icon"
            />
            <image
              v-show="!(detail && detail.hasLiked)"
              src="@/assets/icon/big-like.png"
              class="like-icon"
            />
            <span
              :class="[detail && detail.hasLiked && 'is-active']"
              class="count"
            >
              {{ detail && detail.likeCount }}
            </span>
          </div>

          <div class="operate-item" @tap="onCollect">
            <image
              v-show="detail && detail.hasCollected"
              src="@/assets/icon/big-collect-selected.png"
              class="collect-icon"
            />
            <image
              v-show="!(detail && detail.hasCollected)"
              src="@/assets/icon/big-collect.png"
              class="collect-icon"
            />
            <span
              :class="[detail && detail.hasCollected && 'is-active']"
              class="count"
            >
              {{ detail && detail.collectCount }}
            </span>
          </div>

          <div open-type="share" class="operate-item">
            <button open-type="share" class="share-btn"></button>
            <image src="@/assets/icon/big-share.png" class="share-icon" />
            <span class="count">{{ detail && detail.shareCount }}</span>
          </div>
        </div>
        <div class="safe-bottom"></div>
      </div>
    </div>

    <RateDialog v-model="visible" @close="onClose" />
  </div>
</template>

<script lang="ts">
import RateDialog from "./components/rate-dialog.vue";
export default {
  name: "knowledge-detail",
};
</script>

<script setup lang="ts">
import "./index.less";
import CommonNavigateBar from "@/components/common-navigateBar/index.vue";
import CommonScroll from "@/components/common-scroll/index.vue";
import Taro, { useLoad, useShareAppMessage } from "@tarojs/taro";
import { apiQueryRecommendDetail } from "@/apis/index";
import { computed, ref } from "vue";
import {
  apiAchieveMission,
  apiArticalReview,
  apiCancelCollectArticle,
  apiCancelLikeArticle,
  apiCollectArticle,
  apiLikeArticle,
  apiShareArticle,
} from "@/apis/knowledge";
import { ResponseCodeEnum } from "@/constants/index";
import {
  IArticalDetailRes,
  IArticalReviewReq,
  IMissionRecordReq,
} from "@/apis/types/knowledge";

const detail = ref<IArticalDetailRes | null>(null);
const watchVideoFinished = ref(false);
const isFinished = ref(false);
const visible = ref(false);
const articleId = ref(null);

const html = computed(() => {
  if (!detail.value) return;
  let { rawHtml } = detail.value;
  // return (rawHtml || "").replace(/\<img/gi, '<img style="width: 100%;"');
  return rawHtml || "";
});

useLoad((param) => {
  const { id } = param;
  articleId.value = id;

  queryRecommendDetailServer(id);
});

useShareAppMessage(() => {
  onShareSuccess();
  if (!detail.value) return {};
  return {
    title: "主动健康",
    path: "/packageA/pages/knowledge-detail/index?id=" + detail.value.id,
    imageUrl: "",
  };
});

const onClose = (value: IArticalReviewReq) => {
  if (!articleId.value) return;
  apiArticalReview(articleId.value, value).then((res: any) => {
    const { code } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      Taro.showToast({ title: "评论成功", icon: "success" });
    }
  });
};

const onTimeUpdate = (e: any) => {
  const { currentTime, duration } = e.detail;
  if (currentTime / duration >= 0.8) {
    if (!detail.value || watchVideoFinished.value) return;
    watchVideoFinished.value = true;

    const { categoryId } = detail.value;
    const params: IMissionRecordReq = {
      actionType: "MISSION_READ",
      categoryId: categoryId,
      mainId: articleId.value,
      watchDuration: Math.floor(currentTime),
      isFinished: 1,
    };
    apiAchieveMission(params)
      .then((res: any) => {
        const { code, message } = res;
        if (code === ResponseCodeEnum.SUCCESS) {
        } else {
          Taro.showToast({ title: message, icon: "error" });
        }
      })
      .finally();
  }
};

const onEnded = () => {
  visible.value = true;
};

const onScrollToLower = (done: () => void) => {
  if (!detail.value || isFinished.value) return;
  const { hasReview, videos, categoryId } = detail.value;
  if (videos && videos.length) return;
  if (!hasReview) {
    visible.value = true;
  }

  const params: IMissionRecordReq = {
    actionType: "MISSION_READ",
    categoryId: categoryId,
    mainId: articleId.value,
    watchDuration: null,
    isFinished: 1,
  };
  apiAchieveMission(params)
    .then((res: any) => {
      const { code, message } = res;
      if (code === ResponseCodeEnum.SUCCESS) {
        isFinished.value = true;
      } else {
        Taro.showToast({ title: message, icon: "error" });
      }
    })
    .finally(() => done());
};

const onLike = () => {
  if (!detail.value) return;

  const { hasLiked, id } = detail.value;
  if (hasLiked) {
    apiCancelLikeArticle(id).then((res) => {
      const { code } = res as any;
      if (code === ResponseCodeEnum.SUCCESS) {
        if (!detail.value) return;
        detail.value.hasLiked = false;
        detail.value.likeCount--;
      }
    });
  } else {
    apiLikeArticle(id).then((res) => {
      const { code } = res as any;
      if (code === ResponseCodeEnum.SUCCESS) {
        if (!detail.value) return;
        detail.value.hasLiked = true;
        detail.value.likeCount++;
      }
    });
  }
};

const onCollect = () => {
  if (!detail.value) return;
  const { hasCollected, id } = detail.value;
  if (hasCollected) {
    apiCancelCollectArticle(id).then((res) => {
      const { code } = res as any;
      if (code === ResponseCodeEnum.SUCCESS) {
        if (!detail.value) return;
        detail.value.hasCollected = false;
        detail.value.collectCount--;
      }
    });
  } else {
    apiCollectArticle(id).then((res) => {
      const { code } = res as any;
      if (code === ResponseCodeEnum.SUCCESS) {
        if (!detail.value) return;
        detail.value.hasCollected = true;
        detail.value.collectCount++;
      }
    });
  }
};

const onShareSuccess = () => {
  if (!detail.value) return;

  const { id } = detail.value;
  apiShareArticle(id).then((res) => {
    const { code } = res as any;
    if (code === ResponseCodeEnum.SUCCESS) {
      if (!detail.value) return;
      detail.value.shareCount++;
    }
  });
};

const queryRecommendDetailServer = (id: string) => {
  apiQueryRecommendDetail(id).then((res) => {
    detail.value = res.data;
  });
};
</script>
